<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-date-picker
          style="margin-right: 10px; width: 200px !important; height: 32px; line-height: 32px;"
          v-model="date"
          align="right"
          unlink-panels
          value-format="yyyy-MM-dd">
        </el-date-picker>
        <!--        <el-select style="width: 200px !important; margin-right: 10px" v-model="deliveryStatus" placeholder="请选择物流状态" clearable>-->
        <!--          <el-option :value="'待揽收'" label="待揽收">待揽收</el-option>-->
        <!--          <el-option :value="'运输中'" label="运输中">运输中</el-option>-->
        <!--          <el-option :value="'已签收'" label="已签收">已签收</el-option>-->
        <!--        </el-select>-->
        <el-input placeholder="昵称、电话" style="width: 200px; margin-right: 10px" v-model="nicknameAndPhone" clearable></el-input>
        <el-date-picker
          style="margin-right: 10px; width: 450px !important; height: 32px; line-height: 32px;"
          v-model="dateRange"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions">
        </el-date-picker>
        <el-button type="primary"
                   size="small"
                   @click="onLoad(page)">搜索
        </el-button>
      </template>
      <template slot-scope="{row}" slot="status">
        <el-tag v-if="row.status === 1" type="success">正常</el-tag>
        <el-tag v-if="row.status === 2 && row.cancelConfirmTime !== ''" type="danger">已取消</el-tag>
        <el-tag v-if="row.status === 2 && row.cancelConfirmTime === ''" type="warning">取消未确认</el-tag>
      </template>
      <template slot-scope="{row}" slot="deliveryStatus">
        <el-tag v-if="row.deliveryStatus === 0" type="primary">待配送</el-tag>
        <el-tag v-else-if="row.deliveryStatus === 1" type="warning">配送中</el-tag>
        <el-tag v-else-if="row.deliveryStatus === 99" type="success">配送完成</el-tag>
        <el-tag v-else type="danger">未知</el-tag>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove, cancelSF, routesSF, cancelConfirm} from "@/api/delivery/delivery";
import {mapGetters} from "vuex";
import {dateFormat} from "@/util/date";

const baseTop = 20
export default {
  name: "SendOrder",
  props: {
    row: {
      type: Object,
      default: {}
    },
  },
  data() {
    return {
      logLoading: false,
      logVisible: false,
      logs: [],
      sfAccessToken: '',
      date: '',
      hasSpec: '',
      deliveryStatus: '',
      showCancel: false,
      remark: '',
      nicknameAndPhone: '',
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        refreshBtn: false,
        menu: false,
        selection: true,
        column: [
          {
            label: "日期",
            prop: "date",
            width: 120,
          },
          {
            label: "单号",
            prop: "originNo",
            overHidden: true,
            width: 150,
            rules: [{
              required: true,
              message: "请输入原始单号",
              trigger: "blur"
            }],
            display: false
          },
          {
            label: "门店",
            prop: "merchantId",
            type: "select",
            dicUrl: '/api/merchant/merchant/select',
            props: {
              label: "name",
              value: "id"
            },
          },
          {
            label: "午B餐",
            prop: "meal",
            type: 'radio',
            dicData: [
              {
                label: "A餐",
                value: 1
              },
              {
                label: "B餐",
                value: 2
              },
            ],
          },
          {
            label: "收件人",
            prop: "receiverName",
            rules: [{
              required: true,
              message: "请输入收件人",
              trigger: "blur"
            }]
          },
          {
            label: "收件人手机",
            prop: "receiverPhone",
            width: 150,
            rules: [{
              required: true,
              message: "请输入收件人手机",
              trigger: "blur"
            }]
          },
          {
            label: "收件人地址",
            prop: "receiverAddress",
            width: 150,
            rules: [{
              required: true,
              message: "请输入收件人地址",
              trigger: "blur"
            }]
          },
          {
            label: "状态",
            width: 150,
            prop: "status",
            slot: true,
            display: false
          },
          {
            label: "配送状态",
            prop: "deliveryStatus",
            slot: true,
          },
          {
            label: "订单备注",
            prop: "orderRemark",
            width: 200,
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入订单备注",
              trigger: "blur"
            }]
          },
          {
            label: "创建时间",
            prop: "createTime",
            overHidden: true,
            display: false,
          },
        ]
      },
      data: [],
      dateRange: '',
      pickerOptions: {
        shortcuts: [
          {
            text: '今日',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '明日',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() + 3600 * 1000 * 24);
              end.setTime(end.getTime() + 3600 * 1000 * 24);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '昨日',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              end.setTime(end.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        editBtn: this.vaildData(this.permission.delivery_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  created() {
    const now = new Date()
    now.setTime(now.getTime())
    this.date = dateFormat(now)
  },
  methods: {
    showCancelChange() {
      this.onLoad(this.page)
    },
    handleOpenLog(val) {
      this.logVisible = true
      this.logLoading = true
      routesSF(val.id).then(res => {
        this.logs = res.data.data
        this.logLoading = false
      })
    },
    handleCloseLog() {
      this.logVisible = false
      this.logs = false
    },
    uuid() {
      const temp_url = URL.createObjectURL(new Blob());
      const uuid = temp_url.toString();
      URL.revokeObjectURL(temp_url);
      return uuid.substr(uuid.lastIndexOf("/") + 1);
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleCancelConfirm() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定取消确认?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return cancelConfirm(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleCancelConfirmItem(row) {
      this.$confirm("确定取消确认?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return cancelConfirm(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleCancelSF() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据取消顺丰订单?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return cancelSF(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage){
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize){
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (this.date && this.date !== '') {
        params.date = this.date
      }
      if (this.hasSpec && this.hasSpec !== '') {
        params.hasSpec = this.hasSpec
      }
      if (this.deliveryStatus && this.deliveryStatus !== '') {
        params.deliveryStatus = this.deliveryStatus
      }
      if (this.remark && this.remark !== '') {
        params.remark = this.remark
      }
      if (this.nicknameAndPhone && this.nicknameAndPhone !== '') {
        params.nicknameAndPhone = this.nicknameAndPhone
      }
      if (this.dateRange && this.dateRange !== '') {
        params.startDate = this.dateRange[0]
        params.endDate = this.dateRange[1]
      }
      params.showCancel = this.showCancel
      params.deliverId = this.row.id
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  }
};
</script>

<style lang="scss">
.el-form-item {
  margin-right: 20px;
}
.el-input__icon {
  height: auto;
}
.avue-crud .el-input__inner, .avue-form .el-input__inner {
  height: 32px;
}
.el-select-dropdown .el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
  padding: 0 20px !important;
}
</style>
